import React, { useState, useRef, useEffect } from 'react';

// 会话操作弹窗组件
const SessionMenuModal = ({ session, onEdit, onDelete, onClose, position }) => {
    const modalRef = useRef(null);

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (modalRef.current && !modalRef.current.contains(event.target)) {
                onClose();
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [onClose]);

    return (
        <div
            className="session-modal"
            ref={modalRef}
            style={{
                position: 'absolute',
                top: position.top,
                left: position.left,
                zIndex: 1000
            }}
            onClick={(e) => e.stopPropagation()}
        >
            <div className="session-modal-content">
                <button
                    className="session-modal-item"
                    onClick={() => {
                        onEdit(session.id);
                        onClose();
                    }}
                >
                    <span className="modal-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                        </svg>
                    </span>
                    <span>重命名</span>
                </button>
                <button
                    className="session-modal-item danger"
                    onClick={() => {
                        onDelete(session.id);
                        onClose();
                    }}
                >
                    <span className="modal-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="3,6 5,6 21,6"/>
                            <path d="M19,6v14a2,2 0 0,1-2,2H7a2,2 0 0,1-2-2V6m3,0V4a2,2 0 0,1,2-2h4a2,2 0 0,1,2,2v2"/>
                            <line x1="10" y1="11" x2="10" y2="17"/>
                            <line x1="14" y1="11" x2="14" y2="17"/>
                        </svg>
                    </span>
                    <span>删除</span>
                </button>
            </div>
        </div>
    );
};

const Sidebar = ({
    sessions,
    currentSessionId,
    isLoadingSessions,
    isCreatingSession,
    onCreateSession,
    onSwitchSession,
    onDeleteSession,
    onUpdateSessionTitle,
    onCopySession,
    isVisible
}) => {
    const [editingSession, setEditingSession] = useState(null);
    const [showModal, setShowModal] = useState(null);
    const [modalPosition, setModalPosition] = useState({ top: 0, left: 0 });

    const handleDeleteSession = async (sessionId) => {
        if (!window.confirm('确定要删除这个对话吗？')) return;

        try {
            await onDeleteSession(sessionId);
        } catch (error) {
            alert('删除对话失败，请重试');
        }
    };

    const handleUpdateTitle = async (sessionId, newTitle) => {
        try {
            await onUpdateSessionTitle(sessionId, newTitle);
            setEditingSession(null);
        } catch (error) {
            alert('更新对话失败，请重试');
        }
    };

    const handleMenuClick = (e, sessionId) => {
        e.stopPropagation();

        if (showModal === sessionId) {
            setShowModal(null);
            return;
        }

        // 计算弹窗位置
        const buttonRect = e.currentTarget.getBoundingClientRect();
        const sidebarRect = e.currentTarget.closest('.sidebar').getBoundingClientRect();
        const modalWidth = 160; // 弹窗宽度
        const modalHeight = 150; // 弹窗高度

        // 计算相对于侧边栏的位置
        let top = buttonRect.bottom - sidebarRect.top + 4;
        let left = buttonRect.left - sidebarRect.left - modalWidth;

        // 检查是否会超出边界
        if (left < 8) {
            // 如果左边不够空间，显示在按钮右侧
            left = buttonRect.right - sidebarRect.left + 4;
        }

        // 检查是否会超出右侧边界
        if (left + modalWidth > sidebarRect.width - 8) {
            // 如果右侧不够空间，显示在按钮左侧
            left = buttonRect.left - sidebarRect.left - modalWidth;
        }

        // 检查是否会超出底部边界
        const sidebarHeight = sidebarRect.height;
        if (top + modalHeight > sidebarHeight - 20) {
            // 如果下方不够空间，显示在按钮上方
            top = buttonRect.top - sidebarRect.top - modalHeight - 4;
        }

        // 检查是否会超出顶部边界
        if (top < 8) {
            // 如果上方不够空间，显示在按钮下方
            top = buttonRect.bottom - sidebarRect.top + 4;
        }

        const modalPosition = { top, left };

        setShowModal(sessionId);
        setModalPosition(modalPosition);
    };

    const handleEditClick = (sessionId) => {
        setEditingSession(sessionId);
        setShowModal(null);
    };

    const handleDeleteClick = (sessionId) => {
        handleDeleteSession(sessionId);
    };

    const closeModal = () => {
        setShowModal(null);
    };

    return (
        <>
            <div className={`sidebar ${isVisible ? 'visible' : 'hidden'}`}>
                <div className="sidebar-header">
                    <button
                        className="new-session-btn"
                        onClick={onCreateSession}
                        disabled={isCreatingSession}
                    >
                        {isCreatingSession ? '创建中...' : '+ 新建对话'}
                    </button>
                </div>

                <div className="sessions-list">
                    {isLoadingSessions ? (
                        <div className="loading-sessions">加载中...</div>
                    ) : (
                        sessions.map((session) => (
                            <div
                                key={session.id}
                                className={`session-item ${session.id === currentSessionId ? 'active' : ''}`}
                                onClick={() => onSwitchSession(session.id)}
                            >
                                <div className="session-content">
                                    {editingSession === session.id ? (
                                        <input
                                            type="text"
                                            defaultValue={session.title || '新对话'}
                                            className="session-title-input"
                                            onBlur={(e) => handleUpdateTitle(session.id, e.target.value)}
                                            onKeyDown={(e) => {
                                                if (e.key === 'Enter') {
                                                    handleUpdateTitle(session.id, e.target.value);
                                                }
                                                if (e.key === 'Escape') {
                                                    setEditingSession(null);
                                                }
                                            }}
                                            autoFocus
                                        />
                                    ) : (
                                        <div className="session-info">
                                            <div className="session-title">
                                                {session.title || '新对话'}
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="session-actions">
                                    <button
                                        className="session-menu-btn"
                                        onClick={(e) => handleMenuClick(e, session.id)}
                                    >
                                        ⋯
                                    </button>
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* 用户管理区域 */}
                <div className="sidebar-footer">
                    <div className="user-management">
                        <div className="user-avatar">
                            <span className="material-icons">person</span>
                        </div>
                        <span className="user-management-text">用户管理</span>
                    </div>
                </div>
            </div>

            {/* 弹窗组件 */}
            {showModal && (
                <SessionMenuModal
                    session={sessions.find(s => s.id === showModal)}
                    onEdit={handleEditClick}
                    onDelete={handleDeleteClick}
                    onClose={closeModal}
                    position={modalPosition}
                />
            )}
        </>
    );
};

export default Sidebar;